import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:math';
import 'EventDispatcher.dart';
import 'BodyWidget.dart';
import 'SharedData.dart';

BodyWidget bw=BodyWidget();

class UDP{

  late RawDatagramSocket _socket;
  String deviceIP="192.168.144.10";
  int devicePort=2023;
  TextEditingController textController=TextEditingController();
  TextEditingController textController2=TextEditingController();

  void showInfoDialog(){
    Get.defaultDialog(
      title: "Device WIFI",
      content: Column(children: [
        Row(children: [
          Expanded(child: TextField(controller: textController,decoration: const InputDecoration(hintText: "IP: 192.168.144.10"),),),
        ],),
        Row(children: [
          Expanded(child: TextField(controller: textController2,decoration: const InputDecoration(hintText: "PORT: 2023"),),),
        ],),
      ],
      ),
      onConfirm: (){
        deviceIP=textController.text;
        devicePort=int.parse(textController2.text);
        connect();
        Get.back();
      }
    );
    Timer(const Duration(seconds: 1),(){setBackData();});
  }

  void setBackData(){
    String? storeInfo=SharedData.getData("UDP_IP_PORT");
    if(storeInfo!=null){
      List arr=storeInfo.split("@");
      textController.text=arr[0];
      textController2.text=arr[1];
    }
  }

  void connect() async{
    SharedData.setData("UDP_IP_PORT","$deviceIP@$devicePort");
    RawDatagramSocket.bind("0.0.0.0", 3001).then((socket) {
      print("socket done!");
      _socket=socket;
      _socket.broadcastEnabled=true;
      bw.showConnectState("$deviceIP:$devicePort connected!", 1);
      _socket.listen((RawSocketEvent event){
        if (event == RawSocketEvent.read) {
          final datagram = _socket.receive();

          if (datagram != null) {
            String message = utf8.decode(datagram.data);
            bw.showCallbackInfo(message);
          }
        }
      });
    },
      onError: (e){
        print(e.toString());
        bw.showConnectState("$deviceIP:$devicePort ${e.toString()}", 0);
      });
  }

  void sendData(String str){
    if(_socket!=null){
      print("send DATA $str");
      _socket.send(utf8.encode(str), InternetAddress(deviceIP), devicePort);
    }
  }

  void disconnect(){
    if(_socket!=null){
      _socket.close();
    }
  }

}

class MyUDP extends StatelessWidget{

  @override
  Widget build(BuildContext context) {

    RxString theStr="jack".obs;
    RxInt theIndex=0.obs;

    UDP udp=UDP();

    EventDispatcher.addEventListener("showDialog_udp",(data){
      bw.showCallbackInfo("connecting....");
      udp.showInfoDialog();
    });
    EventDispatcher.addEventListener("disconnect_udp",(data){
      udp.disconnect();
    });
    EventDispatcher.addEventListener("sendData_udp",(data){
      udp.sendData(data);
    });

    return Scaffold(
      appBar: AppBar(title:const Text("UDP"),centerTitle: true,backgroundColor: Colors.deepOrangeAccent, titleTextStyle: const TextStyle(color: Colors.white)),
      body: bw.getWidget(theStr,"udp"),
      bottomNavigationBar: Obx(()=> BottomNavigationBar(items: const [
        BottomNavigationBarItem(icon: Icon(Icons.keyboard_alt_outlined),label: "KEYBOARD"),
        BottomNavigationBarItem(icon: Icon(Icons.compare_arrows),label: "PAN"),
      ],
        onTap: (index){
          if(index==0){
            theStr.value="board";
          }else{
            theStr.value="pan";
          }
          theIndex.value=index;
        },
        currentIndex: theIndex.value,
      )),
    );
  }
}